<script setup lang="ts">
import Motion from "./utils/motion";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { useLayout } from "@/layout/hooks/useLayout";
import { useAuthStoreHook } from "@/store/modules/auth";
import { initRouter, getTopMenu } from "@/router/utils";
import { bg, avatar, illustration } from "./utils/static";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import {
  ref,
  reactive,
  toRaw,
  onMounted,
  onBeforeUnmount,
  nextTick
} from "vue";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import { ElNotification } from "element-plus";
import * as $msgApi from "@/api/sci/msg";
import dayIcon from "@/assets/svg/day.svg?component";
import darkIcon from "@/assets/svg/dark.svg?component";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();
const { initStorage } = useLayout();
initStorage();

const { dataTheme, dataThemeChange } = useDataThemeChange();
dataThemeChange();
const { title } = useNav();
const passIds = ref<string[]>([]);
const statusCounts = ref<Record<number, number>>({});
const authPermission = ref<string[]>([]);
const ruleForm = reactive({
  username: "",
  password: "",
  remember: false
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // useUserStoreHook()
      //   .loginByUsername({ username: ruleForm.username, password: "admin123" })
      //   .then(res => {
      //     if (res.success) {
      //       // 获取后端路由
      //       initRouter().then(() => {
      //         router.push("/");
      //         message("登录成功", { type: "success" });
      //       });
      //     }
      //   });
      useAuthStoreHook()
        .login({
          username: ruleForm.username,
          password: ruleForm.password,
          remember: ruleForm.remember
        })
        .then(res => {
          if (res.success) {
            // 获取后端路由
            initRouter().then(() => {
              router.push(getTopMenu(true).path);
              message("登录成功", { type: "success" });
              getMsg();
            });
          }
        });
    } else {
      loading.value = false;
      return fields;
    }
  });
};
const _delPassMsg = () => {
  $msgApi.del(passIds.value).then(res => {
    if (res.success) message("已确认", { type: "success" });
  });
};

const getMsg = () => {
  authPermission.value = useAuthStoreHook().getPermission();
  $msgApi.msgList().then((res: any) => {
    if (res.success) {
      const msg = res.result;
      passIds.value = msg
        .filter(item => item.status === 5) // 过滤出 status 为 5 的对象
        .map(item => item.id);
      statusCounts.value = msg.reduce((counts, item) => {
        const status = item.status;
        counts[status] = (counts[status] || 0) + 1;
        return counts;
      }, {});
      sendMsg();
    }
  });
};
const sendMsg = async () => {
  if (!authPermission.value) return;

  // 计算待审核和被退回的总数量
  const pendingReviewCount =
    (statusCounts.value[3] || 0) + (statusCounts.value[4] || 0); // 待审核：1 和 3
  const rejectedCount =
    (statusCounts.value[0] || 0) + // 被退回：0
    (statusCounts.value[1] || 0) + // 被退回：2
    (statusCounts.value[2] || 0); // 被退回：4
  const approvedCount = statusCounts.value[5] || 0; // 通过：5

  // 发送"通过"通知
  if (approvedCount > 0) {
    ElNotification({
      title: "通过",
      message: `您有${approvedCount}项申请通过`,
      type: "success",
      offset: 100,
      duration: 0,
      onClose: _delPassMsg // 关闭通知时删除通过的消息
    });
  }
  await nextTick();
  // 发送"被退回"通知
  if (rejectedCount > 0) {
    ElNotification({
      title: "被退回",
      message: `您有${rejectedCount}项申请被退回`,
      type: "error",
      offset: 100
    });
  }
  await nextTick();
  // 发送"待审核"通知
  if (pendingReviewCount > 0) {
    ElNotification({
      title: "待审核",
      message: `您有${pendingReviewCount}项申请待审核`,
      type: "info",
      offset: 100
    });
  }
};
/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
  ruleForm.username = useAuthStoreHook().loginUser.username;
  ruleForm.password = useAuthStoreHook().loginUser.password;
  ruleForm.remember = useAuthStoreHook().loginUser.remember;
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>

<template>
  <div class="select-none">
    <img :src="bg" class="wave" />
    <div class="flex-c absolute right-5 top-3">
      <!-- 主题 -->
      <el-switch
        v-model="dataTheme"
        inline-prompt
        :active-icon="dayIcon"
        :inactive-icon="darkIcon"
        @change="dataThemeChange"
      />
    </div>
    <div class="login-container">
      <div class="img">
        <component :is="toRaw(illustration)" />
      </div>
      <div class="login-box">
        <div class="login-form">
          <avatar class="avatar" />
          <Motion>
            <h2 class="outline-none">{{ title }}</h2>
          </Motion>

          <el-form
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <Motion :delay="100">
              <el-form-item
                :rules="[
                  {
                    required: true,
                    message: '请输入账号',
                    trigger: 'blur'
                  }
                ]"
                prop="username"
              >
                <el-input
                  clearable
                  v-model="ruleForm.username"
                  placeholder="账号"
                  :prefix-icon="useRenderIcon(User)"
                />
              </el-form-item>
            </Motion>

            <Motion :delay="150">
              <el-form-item prop="password">
                <el-input
                  clearable
                  show-password
                  v-model="ruleForm.password"
                  placeholder="密码"
                  :prefix-icon="useRenderIcon(Lock)"
                />
              </el-form-item>
            </Motion>
            <Motion :delay="150">
              <el-form-item prop="remember">
                <div class="w-full h-20px flex justify-between items-center">
                  <el-checkbox v-model="ruleForm.remember"
                    >记住密码</el-checkbox
                  >
                </div>
              </el-form-item>
            </Motion>

            <Motion :delay="250">
              <el-button
                class="w-full mt-4"
                size="default"
                type="primary"
                :loading="loading"
                @click="onLogin(ruleFormRef)"
              >
                登录
              </el-button>
            </Motion>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}
</style>
